//
//  CYShopCartViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/31.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYShopCartViewController.h"
#import "CYShopCartTopView.h"
#import "CYShopCartBottomView.h"
#import "CYDataSourceDelegate.h"
#import "CYShopCartCell.h"
#import "CYTime.h"
#import "CYShopCartAuotCellHight.h"
#import "CYBettingNumber.h"
#import "CYBettingWay.h"
@interface CYShopCartViewController ()<UITableViewDataSource>{
    CYDataSource *_datasource;
    CYDelegate *_delegate;
}
@property (nonatomic, strong) CYShopCartTopView *topView;//随机按钮
@property (nonatomic, strong) CYShopCartBottomView *bottomView;//底部清空按钮
@property (nonatomic, strong) CYImageView *dropRefreshIMG;//下拉刷新
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) CYTime *timer;//倒计时
@property (nonatomic, strong) NSDictionary *lottery_dict;//彩票的所有信息
@property (nonatomic, strong) NSDictionary *personal_data;//个人中心信息，主要获取可用余额
@property (nonatomic, copy) NSString *personal_plistName;//个人中心plist名称

@end

@implementation CYShopCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(245, 245, 250, 1);
    _personal_plistName = @"personal";//我的plist名称
    self.topView.hidden = self.dropRefreshIMG.hidden = NO;
}

- (CYTime *)timer{
    if (!_timer)
        _timer = [[CYTime alloc]init];
    return _timer;
}
- (CYShopCartTopView *)topView{
    if (!_topView) {
        WS(self)
        _topView = [[CYShopCartTopView alloc]initWithColor:[UIColor whiteColor] block:^(ShopCartTopViewActionType type) {
            [weakSelf actionForTopView:type];
        }];
        [self.view addSubview:_topView];
        [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(NAVIBAR_HEIGHT + STATUS_HEIGHT);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(_topView.bounds.size);
        }];
    }
    return _topView;
}

- (CYShopCartBottomView *)bottomView{
    if (!_bottomView) {
        WS(self)
        _bottomView = [[CYShopCartBottomView alloc]initWithColor:[UIColor whiteColor] block:^(ShopCartBottomViewActionType type, int times) {
            [weakSelf actionForBottomView:type];
            [weakSelf setupBettingTimes:times withType:type];
        }];
        [self.view addSubview:_bottomView];
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).with.offset(0);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(_bottomView.bounds.size);
        }];
    }
    return _bottomView;
}

- (CYImageView *)dropRefreshIMG{
    if (!_dropRefreshIMG) {
        _dropRefreshIMG = [[CYImageView alloc]initWithImageName:@"toubag" size:CGSizeMake(SCREEN_WIDTH - AL(PT(42)) * 2, AL(4)) isRadius:NO];
        [self.view addSubview:_dropRefreshIMG];
        
        [_dropRefreshIMG mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom).with.offset(- AL(PT(4)));
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(_dropRefreshIMG.bounds.size);
        }];
    }
    return _dropRefreshIMG;
}

- (UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]init];
        _tableview.mj_header = [CYRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshDown)];//下拉刷新
        
        [self.view addSubview:_tableview];
        [self setupTableview];
        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_dropRefreshIMG.mas_bottom).with.offset(-_dropRefreshIMG.bounds.size.height);
            make.centerX.equalTo(self.view);
            make.width.mas_equalTo(SCREEN_WIDTH - AL(PT(42)) * 2 - AL(8));
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-(AL(PT(66)) + AL(PT(20)) * 2) * 2);
        }];
    }
    return _tableview;
}

- (CYShopCartLotteryModel *)model{
    if (!_model) {
        _model = [[CYShopCartLotteryModel alloc]init];
        _model.ID = _currentBetModel.lotteryID;
        _model.action_No = _currentBetModel.actionNo;
    }
    return _model;
}

- (void)setupTableview{
    WS(self)
    _delegate = [[CYDelegate alloc]initWithAutoHeight:[CYShopCartAuotCellHight cellHights:_model.codes] views:nil block:^(NSIndexPath *index) {
        [weakSelf selectCell:index];
    }];
    _tableview.delegate = _delegate;
    _tableview.dataSource = self;
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview.backgroundColor = [UIColor whiteColor];
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableview registerClass:[CYShopCartCell class] forCellReuseIdentifier:NSStringFromClass([CYShopCartCell class])];
    _tableview.backgroundColor = RGBA(245, 245, 250, 1);
    
}

//绑定cell
- (void)bindCell:(CYShopCartCell *)cell data:(CYSelectLotteryModel *)codeModel{
    cell.number = [NSString specialStringWithArray:[codeModel.actionData componentsSeparatedByString:@","] arrayCharacter:@"   |   " stringCharacter:@","];
    cell.bettingWay =  codeModel.playGroupName;//第一玩法
    cell.detail = codeModel.playName;//第二玩法
    cell.bettingNum = codeModel.actionNum;//注数
    cell.bettingMoney = codeModel.actionNum * codeModel.beiShu * 2;//投注总金额
    cell.bettingTime = codeModel.beiShu;//投注倍数
    
}

//选中cell
- (void)selectCell:(NSIndexPath *)index{
    CYSelectLotteryModel *selectLotteryModel = _model.codes[index.row];
    DeLog(@"号码 %@",selectLotteryModel.actionData);
    
}

//当前彩票所有的玩法信息
- (void)setLottery_dict:(NSDictionary *)lottery_dict{
    if (!lottery_dict){
        _lottery_dict = [CYCache getCache:[NSString stringWithFormat:@"%@_玩法",_lottery_name]];//从本地读取缓存
        if (!_lottery_dict)
            return;
    }
    else if (_lottery_dict != lottery_dict)
        _lottery_dict = lottery_dict;
    WS(self)
    _topView.date = [NSString getClosingDate:_currentBetModel.actionNo];//期数
    [self.timer countDown:_currentBetModel.endTime time:^(NSString *time) {
        weakSelf.topView.time = time;//倒计时
    } complete:^{
        
    }];
    [CYCache cache:_lottery_dict plist:[NSString stringWithFormat:@"%@_玩法",_lottery_name] ];//缓存
    
}

//更新模型
- (void)updateArrayOfModel{
    [self ergodicModelWithBeiShu:0];
}

//遍历模型，获取总注数和总金额
- (void)ergodicModelWithBeiShu:(int)beiShu{
    int num = 0;
    int money = 0;
    for (CYSelectLotteryModel *subCodeModel in _model.codes) {
        subCodeModel.beiShu = (subCodeModel.beiShu < 2 && beiShu < 0)?subCodeModel.beiShu:subCodeModel.beiShu + beiShu;
        num += subCodeModel.actionNum;
        money += subCodeModel.actionNum * subCodeModel.beiShu * 2;
    }
    self.bottomView.bettingNum = (int)num;
    self.bottomView.bettingMoney = (int)money;
    [self.tableview reloadData];
    
}

//倍数
- (void)setupBettingTimes:(int)times withType:(ShopCartBottomViewActionType)type{
    if (type == MinusOrPlusAction && _model.codes.count > 0)//加倍数
        [self ergodicModelWithBeiShu:times];
}

//topview按钮事件//随机一注||随机无注||自选号码
- (void)actionForTopView:(ShopCartTopViewActionType )type{
    if (type == SuiJiYiZhu)
        [self randomNumber:1];
    else if (type == SuiJiWuZhu)
        [self randomNumber:5];
    else
        [self popPreviousViewController];
}

//bottom按钮事件
- (void)actionForBottomView:(ShopCartBottomViewActionType )type{
    if (type == CleanAction)//清空
        [CYAlert showInWindowWithTitle:@"注意" message:@"点击确定清除所有订单" enterComplete:^{
            [self clearSelectDict];
        }];
    else if (type == PayAction)//投注
        [self betHttps];
}

//
- (void)refreshDown{
    [self randomNumber:1];
    [_tableview.mj_header endRefreshing];
}
//随机
- (void)randomNumber:(NSUInteger)count{
    for (int i = 0; i < count; i ++) {
        //随机生成的号码数组
        NSMutableArray *randomArr = [CYBettingNumber getRandomSource:_currentBetModel.playedGroupId
                                                    playedIdentifier:_currentBetModel.playedTpl
                                                             cellArr:_currentBetModel.cellArr];
        //将随机生成的号码数组，转换成字符串，
        NSString * actionData = [CYBettingNumber stringWithArray:randomArr playedIdentifier:_currentBetModel.playedTpl];
        //构建请求数组
        NSDictionary *subPara = @{@"actionData":actionData,//投注号码
                                  @"fanDian":@(0),//返利
                                  @"beiShu":@(1),//倍数
                                  @"actionNum":@(1),//注数
                                  @"actionPrice":@(2),//投注总金额(除以倍数，后台会自动乘以倍数)
                                  @"onePrice":@(2),//单注金额
                                  @"playedId":@(_currentBetModel.secondBetID),//玩法id
                                  @"playedGroup":@(_currentBetModel.firstBetID),//玩法组id
                                  @"bonusProp":@(_currentBetModel.bonusProp),//赔率
                                  @"mode":@(2),//数2元0.2角0.02分
                                  @"playGroupName":_currentBetModel.firstBetName,//一级玩法名称
                                  @"playName":_currentBetModel.secondBetName};//二级玩法名称
        CYSelectLotteryModel *subCodeModel = [CYSelectLotteryModel mj_objectWithKeyValues:subPara];
        [self.model.codes insertObject:subCodeModel atIndex:0];
    }
    [self updateArrayOfModel];
    
}
//点击清除按钮，或者投注成功后，清除购彩车里选中的号码
- (void)clearSelectDict{
    [_model.codes removeAllObjects];
    [self updateArrayOfModel];
    self.bottomView.bettingNum = 0;
}

#pragma mark - UITableViewDatasource事件
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _model.codes.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = NSStringFromClass([CYShopCartCell class]);
    CYShopCartCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (!cell) {
        Class cellClass = NSClassFromString(identifier);
        cell = [[cellClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.width = SCREEN_WIDTH - AL(PT(42)) * 2 - AL(8);
    [self bindCell:(CYShopCartCell *)cell data:_model.codes[indexPath.row]];
    cell.bottomIMG.hidden = (_model.codes.count == indexPath.row + 1)?NO:YES;
    return cell;
    
}

//左滑删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    [_model.codes removeObjectAtIndex:indexPath.row];    // 删除模型
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];    // 刷新
    [self updateArrayOfModel];//更新tableviewbounds
}

//请求投注页,获取倒计时，期数
- (void)https{
    if (!_lottery_id)
        return;
    self.spareTask = [CYHttps POST:API_betIndex parameters:@{@"id":_lottery_id} showHUD:NO progress:nil success:^(id data) {
        self.lottery_dict = data;
    } failure:^(id string) {
        self.lottery_dict = nil;
    }];
}

//请求投注
- (void)betHttps{
    
    self.task = [CYHttps POST: API_bet parameters:@{@"data":[NSDictionary jsonWithDict:[_model mj_keyValues]]} showHUD:YES progress:nil success:^(id data) {
        if (data)
            [CYSuccessTipsView showTitle:@"投注成功" buttonTitle:@"确定" block:^{
                [self clearSelectDict];
                [self popPreviousViewController];
            }];
    } failure:nil];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self ergodicModelWithBeiShu:0];
    [self https];
    //    [self userHttps];
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    _block(_model.codes.count, [_model mj_keyValues]);//返回购彩车里有多少组选中的号码
    [self.timer cancel];
}

- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:color];
    self.title = @"购物车";
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
